import { createRouter, createWebHistory } from "vue-router";

const Login = () => import("@/views/Login");
const Home = () => import("@/views/Home");
const Welcome = () => import("@/views/Welcome");
const Echarts = () => import("@/views/Echarts");
const Blog = () => import("@/views/Blog");
const Publish = () => import("@/views/Publish");
const Err = () => import("@/views/Err");
const routes = [
	{
		path: "/",
		redirect: "/login",
	},
	{
		path: "/login",
		component: Login,
	},
	{
		path: "/home",
		component: Home,
		redirect: "/welcome",
		children: [
			{ path: "/welcome", component: Welcome },
			{ path: "/echarts", component: Echarts },
			{ path: "/blog", component: Blog },
			{ path: "/publish", component: Publish },
		],
	},
	{
		path: "/:catchAll(.*)",
		name: "Err",
		component: Err,
	},
];

const router = createRouter({
	history: createWebHistory(process.env.BASE_URL),
	routes,
});

router.beforeEach((to, from, next) => {
	/* to 将要访问的路径
	 * from 代表从哪个路径跳转而来
	 * next() 放行 */
	if (to.path === "/login") return next();
	const tokenStr = window.localStorage.getItem("blog_publish_token");
	if (!tokenStr) return next("/login");
	next();
});

export default router;
